﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.FileProviders;
using SysIO=System.IO;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;

namespace VOL.WebApi.Controllers
{
    public class FileHelper
    {
        private readonly IFileProvider _fileProvider;

        public FileHelper(IFileProvider fileProvider)
        {
            _fileProvider = fileProvider;
        }

        public async Task<Dictionary<bool,string>> UploadFile(IFormFile file, string? uploadFolder)
        {
            if (file == null || file.Length == 0)
            {
                return new Dictionary<bool, string> { { false, "无效的文件" } };
            }
            if (string.IsNullOrEmpty(uploadFolder))
            {
                uploadFolder = "";
            }

            EnsureUploadsFolderExists(uploadFolder); // 确保上传文件夹存在

            var filePath = Path.Combine(GetRootPath() + uploadFolder, file.FileName);

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
            return new Dictionary<bool, string> { { true, "文件上传成功" } };
        }

        public byte[] DownloadFile(string fileName)
        {
            var filePath = Path.Combine("", fileName);
            var physicalPath = Path.Combine(GetRootPath(), filePath);

            if (_fileProvider.GetFileInfo(filePath).Exists)
            {
                return SysIO.File.ReadAllBytes(physicalPath);
              
            }

            return null;
        }

        public Dictionary<bool, string> CreateFolder(string folderPath)
        {
            if (string.IsNullOrEmpty(folderPath))
            {
                return new Dictionary<bool, string> { { false, "文件不存在" } };
            }

            if (!_fileProvider.GetDirectoryContents(folderPath).Exists)
            {
                SysIO.Directory.CreateDirectory(GetRootPath() + folderPath);
                return new Dictionary<bool, string> { { true, "文件创建成功" } };
            }

            return new Dictionary<bool, string> {{false,$"文件夹 '{folderPath}' 已经存在"}};
        }

        public bool FolderExists(string folderPath)
        {

            return _fileProvider.GetDirectoryContents(folderPath).Exists;
        }

        public IDirectoryContents GetFileList(string path = "")
        {
            return  _fileProvider.GetDirectoryContents(path);
        }

        public string GetRootPath()
        {
            var path = ((PhysicalFileProvider)_fileProvider).Root;
            return path;
        }

        private void EnsureUploadsFolderExists(string path)
        {
            var uploadsPath = path;
            if (!_fileProvider.GetDirectoryContents(uploadsPath).Exists)
            {
                SysIO.Directory.CreateDirectory(uploadsPath);
            }
        }
    }
}
